package com.taotao.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.common.utils.CookieUtils;
import com.taotao.pojo.TbUser;
import com.taotao.portal.service.impl.UserServiceImpl;

public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private UserServiceImpl userService;

	// handler之前执行
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
// 判断用户是否登录
		// 1. 从cookie取token
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		// 根据token获取用户信息
		TbUser user = userService.getUserByToken(token);
		// 判断，若user为空，跳转登录页
		if (null == user) {
			System.out.println("*******************************************");
			System.out.println("*******************************************");
			System.out.println("*******************************************");
			response.sendRedirect(
					userService.SSO_BASE_URL + userService.SSO_USER_LOGIN + "?redirect=" + request.getRequestURL());
			System.out.println(userService.SSO_BASE_URL + userService.SSO_USER_LOGIN + "?redirect=" + request.getRequestURL());
			return false;

		}
		request.setAttribute("user", user);
		return true;
	}

	// handler之后，返回ModelAndView之前执行
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	// 返回ModelAndView之后执行
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
